package service

import (
	"context"
	pb "medicine/api/medicine/v1"
	"medicine/internal/biz"
)

// CategoryService 分类服务实现，处理分类相关的 gRPC 请求
// 调用 usecase 层实现具体业务逻辑
type CategoryService struct {
	pb.UnimplementedCategoryServer                      // gRPC 分类服务基类
	uc                             *biz.CategoryUsecase // 分类用例层依赖
}

// NewCategoryService 创建分类服务实例
func NewCategoryService(uc *biz.CategoryUsecase) *CategoryService {
	return &CategoryService{uc: uc}
}

// CreateCategory 创建分类
func (s *CategoryService) CreateCategory(ctx context.Context, req *pb.CreateCategoryRequest) (*pb.CategoryReply, error) {
	c := &biz.Category{
		Name: req.Name,
	}
	newC, err := s.uc.Create(ctx, c)
	if err != nil {
		return nil, err
	}
	return &pb.CategoryReply{
		Id:   newC.ID,
		Name: newC.Name,
	}, nil
}

// GetCategory 获取分类详情
func (s *CategoryService) GetCategory(ctx context.Context, req *pb.GetCategoryRequest) (*pb.CategoryReply, error) {
	c, err := s.uc.Get(ctx, req.Id)
	if err != nil {
		return nil, err
	}
	return &pb.CategoryReply{
		Id:   c.ID,
		Name: c.Name,
	}, nil
}

// UpdateCategory 更新分类
func (s *CategoryService) UpdateCategory(ctx context.Context, req *pb.UpdateCategoryRequest) (*pb.CategoryReply, error) {
	c := &biz.Category{
		ID:   req.Id,
		Name: req.Name,
	}
	newC, err := s.uc.Update(ctx, c)
	if err != nil {
		return nil, err
	}
	return &pb.CategoryReply{
		Id:   newC.ID,
		Name: newC.Name,
	}, nil
}

// DeleteCategory 删除分类
func (s *CategoryService) DeleteCategory(ctx context.Context, req *pb.DeleteCategoryRequest) (*pb.DeleteCategoryReply, error) {
	err := s.uc.Delete(ctx, req.Id)
	return &pb.DeleteCategoryReply{Success: err == nil}, err
}

// ListCategory 分页获取分类列表
func (s *CategoryService) ListCategory(ctx context.Context, req *pb.ListCategoryRequest) (*pb.ListCategoryReply, error) {
	categories, total, err := s.uc.List(ctx, int(req.Page), int(req.PageSize))
	if err != nil {
		return nil, err
	}
	var replies []*pb.CategoryReply
	for _, c := range categories {
		replies = append(replies, &pb.CategoryReply{
			Id:   c.ID,
			Name: c.Name,
		})
	}
	return &pb.ListCategoryReply{Categories: replies, Total: int32(total)}, nil
}
